
package com.zjxd.business.web.api.user;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zjxd.business.web.code.ApiResultCode;
import com.zjxd.business.web.common.ApiResult;
import com.zjxd.business.web.common.BaseService;
import com.zjxd.business.web.model.pojo.TBFunds;
import com.zjxd.business.web.model.pojo.TBUser;
import com.zjxd.business.web.model.pojo.TBUserExample;
import com.zjxd.business.web.utils.CoreUtil;
import com.zjxd.business.web.utils.TimeUtil;

@Service
@Transactional
public class ApiUserServiceImpl extends BaseService implements ApiUserService {

	/**
	 * 分页查询用户数据
	 */
	public ApiResult getAll(ApiUserModel model) {

	
		TBUserExample example = new TBUserExample();
		if(!StringUtils.isEmpty(model.getPhone())){
			example.createCriteria().andUserphoneLike(model.getPhone());
		}
		if(model.getStartTime()!=null && model.getEndTime()!=null){
			example.createCriteria().andCreatetimeNotBetween(model.getStartTime(), model.getEndTime());
		}
		example.setOrderByClause("createtime desc");
		PageHelper.startPage(model.getPageNum(), model.getPageSize());
		List<TBUser> userList = tBUserMapper.selectByExample(example);
		PageInfo<TBUser> pageInfo = new PageInfo<>(userList);
		return ApiResult.success(pageInfo);
	}

	/**
	 * 批量删除用户数据
	 */
	public ApiResult deleteByIds(String ids) {

		if (CoreUtil.isBlank(ids)) { return ApiResult.fail("请选择需要删除的用户"); }
		List<Long> userId = new ArrayList<Long>();
		String[] id = ids.split(",");
		for (int i = 0; i < id.length; i++) {
			userId.add(Long.parseLong(id[i]));
		}
		TBUserExample example = new TBUserExample();
		example.createCriteria().andUseridIn(userId);
		return ApiResult.success(tBUserMapper.deleteByExample(example));
	}

	/**
	 * 新增用户信息
	 */
	public ApiResult insert(TBUser tBUser) {

		TBUser entity = new TBUser();
		entity.setUsername(tBUser.getUsername());
		if(tBUserMapper.selectCount(entity)>0){//用户名重复
			return ApiResult.fail("用户名重复");
		}
		entity = new TBUser();
		entity.setUserphone(tBUser.getUserphone());
		if(tBUserMapper.selectCount(entity)>0){//用户电话号码重复
			return ApiResult.fail("用户手机号重复");
		}
		tBUser.setEnabled((long)1);
		tBUser.setLastlogintime(new Date());
		tBUser.setBirthday(new Date());
		return ApiResult.success(tBUserMapper.insertSelective(tBUser));
	}

	/**
	 * 更新用户信息
	 */
	public ApiResult update(TBUser tBUser) {

		return ApiResult.success(tBUserMapper.updateByPrimaryKeySelective(tBUser));
	}

	/**
	 * 跟新用户余额
	 */
	public ApiResult updateBalance(TBUser tBUser) {

		// 根据用户id获得用户信息
		TBUser user = tBUserMapper.selectByPrimaryKey(tBUser.getUserid());
		if (user == null) { return ApiResult.fail("用户不存在"); }
		BigDecimal blance = user.getBalance();
		// 设置充值后的用户余额
		user.setBalance(blance.add(new BigDecimal(tBUser.getMoney())));

		// 跟新用户余额
		int falge = tBUserMapper.updateByPrimaryKeySelective(user);
		if (falge == 1) {   // 跟新成功以后，添加充值表信息
			TBFunds tBFunds = new TBFunds();
			tBFunds.setBalance(blance.add(new BigDecimal(tBUser.getMoney())));
			tBFunds.setFee(new BigDecimal(tBUser.getMoney()));
			tBFunds.setUserid(tBUser.getUserid());
			tBFunds.setCreatetime(new Date());
			tBFunds.setFundstype(4L);
			// 新增充值信息，并返回结果
			//tBFundsMapper.insertSelective(tBFunds);
			return ApiResult.success(tBFundsMapper.insertSelective(tBFunds));
		} else {
			return ApiResult.fail(ApiResultCode.fail_code);
		}
	}

	/**
	 * 批量导出用户信息
	 */
	@SuppressWarnings({"resource"})
	public int export(String ids, HttpServletResponse response) {

		// 将字符串转换成整型数组
		String[] id = ids.split(",");
		List<Long> idList = new ArrayList<Long>();
		for (int i = 0; i < id.length; i++) {
			idList.add(Long.parseLong(id[i]));
		}

		// 获得用户列表
		List<TBUser> varlogList = tBUserMapper.listAllByIds(idList);
		// 创建workbook
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 创建sheet页
		HSSFSheet sheet = workbook.createSheet("用户列表");

		// 创建单元格
		HSSFRow row = sheet.createRow(0);
		HSSFCell c0 = row.createCell(0);
		c0.setCellValue(new HSSFRichTextString("用户账号"));

		HSSFCell c1 = row.createCell(1);
		c1.setCellValue(new HSSFRichTextString("用户电话"));

		HSSFCell c2 = row.createCell(2);
		c2.setCellValue(new HSSFRichTextString("用户类型"));

		HSSFCell c3 = row.createCell(3);
		c3.setCellValue(new HSSFRichTextString("账户余额"));

		HSSFCell c4 = row.createCell(4);
		c4.setCellValue(new HSSFRichTextString("最后一次登录时间"));

		HSSFCell c5 = row.createCell(5);
		c5.setCellValue(new HSSFRichTextString("注册时间"));

		int num = 1;
		for (int i = 0; i < varlogList.size(); i++) {

			// 获得用户数据
			TBUser tBUser = varlogList.get(i);

			// 创建行对象
			HSSFRow rownum = sheet.createRow(num);

			HSSFCell cnum0 = rownum.createCell(0);
			cnum0.setCellValue(new HSSFRichTextString(tBUser.getUsername()));

			HSSFCell cnum1 = rownum.createCell(1);
			cnum1.setCellValue(new HSSFRichTextString(tBUser.getUserphone()));

			HSSFCell cnum2 = rownum.createCell(2);
			cnum2.setCellValue(new HSSFRichTextString("APP"));

			HSSFCell cnum3 = rownum.createCell(3);
			cnum3.setCellValue(new HSSFRichTextString(tBUser.getBalance().toString()));

			HSSFCell cnum4 = rownum.createCell(4);
			if (tBUser.getLastlogintime() != null && !tBUser.getLastlogintime().equals("")) {
				cnum4.setCellValue(new HSSFRichTextString(TimeUtil.format(tBUser.getLastlogintime(), TimeUtil.FORMAT_LONG)));
			} else {
				cnum4.setCellValue(new HSSFRichTextString("-"));
			}

			HSSFCell cnum5 = rownum.createCell(5);
			if (tBUser.getCreatetime() != null && !tBUser.getCreatetime().equals("")) {
				cnum5.setCellValue(new HSSFRichTextString(TimeUtil.format(tBUser.getCreatetime(), TimeUtil.FORMAT_LONG)));
			} else {
				cnum5.setCellValue(new HSSFRichTextString("-"));
			}
			num++;
		}

		// 第六步，将文件存到指定位置
		try {
			Calendar cal = Calendar.getInstance();
			String fileName = "用户信息" + cal.get(Calendar.YEAR) + "年" + (cal.get(Calendar.MONTH) + 1) + "月" + cal.get(Calendar.DATE) + "日" + cal.get(Calendar.HOUR_OF_DAY) + "时" + cal.get(Calendar.MINUTE) + "分" + cal.get(Calendar.SECOND) + "秒" + ".xls";;
			fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);// 指定下载的文件名
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			OutputStream output = response.getOutputStream();
			workbook.write(output);
			output.flush();
			output.close();
		} catch (Exception e) {
			return 0;
		}
		return 1;
	}
}
